package data;

import org.jboss.netty.buffer.ChannelBuffer;

import util.ChannelBufferUtil;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;

public class SGPet implements ISerializable {
	public static void writeFromDB(ChannelBuffer buf, BasicDBObject db) {
		buf.writeInt(db.getInt("nature"));
		buf.writeInt(db.getInt("profession"));
		buf.writeInt(db.getInt("level"));
		buf.writeInt(db.getInt("grow"));
		buf.writeInt(db.getInt("figureID"));
		
		BasicDBList list = (BasicDBList)db.get("currentSkill");
		int t;
		buf.writeInt(list.size());
		for (int i = 0; i < list.size(); i++) {
			t = (Integer)list.get(i);
			buf.writeInt(t);
		}
		
		list = (BasicDBList)db.get("currentEquips");
		buf.writeInt(list.size());
		BasicDBObject tb;
		for (int i = 0; i < list.size(); i++) {
			tb = (BasicDBObject)list.get(i);
			buf.writeInt(tb.getInt("ID"));
			buf.writeInt(tb.getInt("level"));
		}
		
		list = (BasicDBList)db.get("currentElements");
		buf.writeInt(list.size());
		for (int i = 0; i < list.size(); i++) {
			tb = (BasicDBObject)list.get(i);
			buf.writeInt(tb.getInt("ID"));
			buf.writeInt(tb.getInt("quality"));
			buf.writeInt(tb.getInt("level"));
		}
		buf.writeInt(db.getInt("quality"));
	}
	
	public BasicDBObject db;
	
	@Override
	public void serialize(ChannelBuffer buf) {
		// TODO Auto-generated method stub
		
	}
	
	public int[] equipLevel;
	public int level;

	@Override
	public void unserialize(ChannelBuffer buf) {
	    db.put("ID", buf.readInt());
	    db.put("nature", buf.readInt());
	    db.put("profession", buf.readInt());//ְҵ
	    level = buf.readInt();
	    db.put("level", level);
	    
	    int count = buf.readInt();
	    int[] skills = new int[count];
	    for (int i = 0; i < count; i++) {
	    	skills[i] = buf.readInt();
	    }
	    db.put("currentSkill", skills);
	    
	    db.put("petIdentifier", ChannelBufferUtil.readString(buf));
	    db.put("petType", buf.readInt());
	    db.put("currentEXP", buf.readInt());
	    db.put("grow", buf.readInt());
	    db.put("figureID", buf.readInt());
	    
	    count = buf.readInt();
	    BasicDBObject[] equips = new BasicDBObject[count];
	    equipLevel = new int[count];
	    for (int i = 0; i < count; i++) {
	    	equips[i] = SGEquip.readToDBObject(buf);
	    	equipLevel[i] = equips[i].getInt("level");
	    }
	    db.put("currentEquips", equips);
	    
	    
	    count = buf.readInt();
	    BasicDBObject[] currentElements = new BasicDBObject[count];
	    for (int i = 0; i < count; i++) {
	    	currentElements[i] = new BasicDBObject();
	    	SGElement.readToDBObject(buf, currentElements[i]);
	    }
	    db.put("currentElements", currentElements);
	    
	    db.put("quality", buf.readInt());
	}

}
